package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpLogMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import com.itheima.utils.TliasException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogService empLogService;
    @Autowired
    private EmpLogMapper empLogMapper;

    @Override
    public PageResult page(EmpQueryParam empQueryParam) {
        // 1. 设置分页参数
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());

        // 2. 执行查询，返回List<Emp>
        List<Emp> empList = empMapper.page(empQueryParam);

        // 3. 封装分页结果
        Page<Emp> page = (Page<Emp>) empList;

        // 4. 返回PageResult对象
        return new PageResult(page.getTotal(), page.getResult());
    }


    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void save(Emp emp) {
        try {
            //1.补全基础属性
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());

            //2.保存员工基本信息
            empMapper.insert(emp);


            //3. 保存员工的工作经历信息 - 批量
            Integer empId = emp.getId();
            List<EmpExpr> exprList = emp.getExprList();
            if (!CollectionUtils.isEmpty(exprList)) {
                exprList.forEach(empExpr -> empExpr.setEmpId(empId));
                empExprMapper.insertBatch(exprList);
            }
        } finally {
//记录操作日志
            EmpLog empLog = new EmpLog(null, LocalDateTime.now(), emp.toString());
            empLogService.insertLog(empLog);

        }

    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void insertLog(EmpLog empLog) {
        empLogMapper.insert(empLog);
    }

    @Transactional
    @Override
    public void deleteByIds(List<Integer> ids) {
        //1. 根据ID批量删除员工基本信息
        empMapper.deleteByIds(ids);

        //2. 根据员工的ID批量删除员工的工作经历信息
        empExprMapper.deleteByEmpIds(ids);
    }
    @Override
    public Emp getInfo(Integer id) {
        // 查询员工的基本信息
        Emp emp = empMapper.getById(id);

        // 根据员工的id查询工作经历
        List<EmpExpr> exprList = empExprMapper.getByEmpId(id);

        emp.setExprList(exprList);

        return emp;

    }
    @Transactional
    @Override
    public void update(Emp emp) {
        //1. 根据ID更新员工基本信息
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateById(emp);

        //2. 根据员工ID删除员工的工作经历信息 【删除老的】
        empExprMapper.deleteByEmpIds(Arrays.asList(emp.getId()));

        //3. 新增员工的工作经历数据 【新增新的】
        Integer empId = emp.getId();
        List<EmpExpr> exprList = emp.getExprList();
        if(!CollectionUtils.isEmpty(exprList)){
            exprList.forEach(empExpr -> empExpr.setEmpId(empId));
            empExprMapper.insertBatch(exprList);
        }
    }

//    public JobOption empjobData(){
//        JobOption jobOption =new JobOption();
//
//        List jobList =new ArrayList();
//        List dataList =new ArrayList();
//        for (Mao map :mapList){
//            jobList.add(map.get("jobName"));
//            dataList.add(map.get("nums"));
//        }
//        jobOption.setJobList(jobList);
//        jobOption.setDataList(dataList);
//
//        return jobOption;
//    }

    @Override
    public JobOption getEmpJobData() {
        List<Map<String,Object>> list = empMapper.countEmpJobData();
        List<Object> jobList = list.stream().map(dataMap -> dataMap.get("jobName")).toList();
        List<Object> dataList = list.stream().map(dataMap -> dataMap.get("total")).toList();
        return new JobOption(jobList, dataList);
    }

    @Override
    public List<Map> getEmpGenderData() {
        return empMapper.countEmpGenderData();
    }

    @Override
    public List<Emp> list() {
        return empMapper.list();
    }

    @Override
    public LoginInfo login(EmpDto empDto) {
        // 根据用户名和密码查询emp  最多查到一个
        Emp emp =  empMapper.findEmpByUsernameAndPassword(empDto.getUsername(),empDto.getPassword());

        // 如果没有查到 用户名或密码错误
        if(emp==null){
            throw new TliasException("用户名或密码错误"); //看今天讲义1.5章节自定义异常
        }

        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setId(emp.getId());
        loginInfo.setName(emp.getName());
        loginInfo.setUsername(emp.getUsername());

        Map<String,Object> claims= new HashMap();
        claims.put("userId",emp.getId());
        claims.put("name",emp.getName());
        String token = JwtUtils.generateJwt(claims); // 使用工具类生成token字符串
        loginInfo.setToken(token);

        return loginInfo;
    }






}
